<?php

namespace app\api\controller;
use app\model\CodeModel;
use think\App;


class Code extends Base {

    private $req;

    private $ip;

    private $codeModel;



    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->req = request()->param();

        $this->ip = request()->ip();

        $this->codeModel = new CodeModel();
    }

    /*
     * 发送验证码
     *
     * */
    public function sendCode(){

        if(!verification_mobile($this->req['mobile'])){
            return $this->fail("手机号格式错误");
        }

        if(!$this->codeModel->isMobileTodayCanSend($this->req['mobile'])){
            return $this->fail("手机号今日发送验证码次数已达到最大次数");
        }

        if(!$this->codeModel->isIpTodayCanSend($this->ip)){
            return $this->fail("IP今日发送验证码次数已达到最大次数");
        }

        if($this->codeModel->hasVerifyMobileCode($this->req['mobile'])){
            return $this->fail("验证码已发送，请勿重复点击！");
        }


        $code = $this->codeModel->generateCode();

        $message =  $this->codeModel->generateSendCodeMsg($code);

        if(!sendSms($this->req['mobile'],$message)){
            return $this->fail("验证码发送失败");
        }

        //发送成功
        $this->codeModel->setVerifyMobileCode($this->req['mobile'],$code);

        $this->codeModel->incrMobileTodaySendNum($this->req['mobile']);

        $this->codeModel->incrIpTodaySendNum($this->ip);

        return $this->success(null,"验证码发送成功");
    }






}